<?php

namespace app\socketio\controller;

use Workerman\Worker;
use Workerman\Lib\Timer;
use think\Controller;
use app\common\AudioFileAllOperation;
use app\common\Content;
use app\common\cache\RedisPackage;
use app\api\model\LiveSpeech1;

//服务端

class Merge extends Controller
{
    protected static $redis;

    public function index()
    {
        $worker = new Worker();

        $worker->onWorkerStart = function () {
            Timer::add(5, function () {
                $this->handler();
            });
        };
        // 运行worker
        Worker::runAll();
    }

    public function handler()
    {
        while (($file_attr = $this->FilePopFromList())) {
            $this->mergeStart($file_attr);
        }
    }

    public function mergeStart($file)
    {
        try {
            $live_model = LiveSpeech1::get($file['id']);
            if ($live_model->transition_state != 4) {
                return;
            }
            $this->mergeFileHandler($live_model);
            $this->mergeTextEditHandler($live_model);
            $live_model->transition_state = 5;
            $live_model->update_time = time();
            $live_model->end_time = time();
            $live_model->save();
        } catch (\Exception $e) {
            $live_model = LiveSpeech1::get($file['id']);
            $live_model->transition_state = 3;
            $live_model->update_time = time();
            $live_model->save();
        }
    }

    //合并文件
    // private function mergeFileHandler($live, $separats)
    // {
    //     $filelist = array();
    //     foreach ($separats as $separat) {
    //         $filelist[] = config('share_path') . config('huisheng.box_audio_dir') . DS . $separat->formatname;
    //     }
    //     $out_path = config('share_path') . config('huisheng.box_audio_dir') . DS . $live->formatname . '.wav';
    //     //合并文件
    //     AudioFileAllOperation::mergerWaves($filelist, $out_path);
    //     $seconds = AudioFileAllOperation::waveDetailLength($out_path);
    //     if (!is_dir(config('share_path') . config('huisheng.upload_mp3_path') . DS . $live->uid)) {
    //         mkdir(config('share_path') . config('huisheng.upload_mp3_path') . DS . $live->uid, 0777, true);
    //     }
    //     $mp3_path = config('share_path') . config('huisheng.upload_mp3_path') . DS . $live->uid . DS . pathinfo($out_path)['filename'] . ".mp3";
    //     AudioFileAllOperation::wavTrans2Another($out_path, $mp3_path);
    //     $json_path = config('share_path') . config('huisheng.upload_mp3_path') . DS . $live->uid . DS . pathinfo($out_path)['filename'] . ".json";
    //     AudioFileAllOperation::wave2json($out_path, $json_path, $seconds);

    //     //保存
    //     $live->seconds = $seconds;
    //     $live->size = filesize($out_path);
    //     $live->save();
    // }

    public function mergeFileHandler($live)
    {
        //遍历实时音频列表，集合合并
        $list = array();
        foreach ($live->mconvert()->field("url")->order('sorting asc')->select() as $piece) {
            $filepath = config('huisheng.base_dir') . $piece->url;
            if (is_file($filepath)) {
                array_push($list, $filepath);
            } else {
                echo "文件 $live->id 分片文件 $piece->url 不存在";
            }
        }
        if(!$list){
            $live->seconds = 0;
            $live->size = 0;
            $live->save();
        }
        //合并文件
        $seconds = $live->mconvert()->sum('pcmtime');
        if (!is_dir(config('share_path') . config('huisheng.upload_mp3_path') . DS . $live->uid)) {
            mkdir(config('share_path') . config('huisheng.upload_mp3_path') . DS . $live->uid, 0777, true);
        }
        $mp3_path = config('share_path') . config('huisheng.upload_mp3_path') . DS . $live->uid . DS . $live->formatname . ".mp3";
        AudioFileAllOperation::mergerWaves($list, $mp3_path);
        $wav_path = config('share_path') . config('huisheng.box_audio_dir') . DS . $live->formatname . '.wav';

        AudioFileAllOperation::moveFileandTrans2Wav($mp3_path, $wav_path);
        $json_path = config('share_path') . config('huisheng.upload_mp3_path') . DS . $live->uid . DS . $live->formatname . ".json";
        AudioFileAllOperation::wave2json($wav_path, $json_path, $seconds);

        //保存
        $live->seconds = $seconds;
        $live->size = filesize($mp3_path);
        $live->save();
    }

    //合并文字 未修改
    private function mergeTextHandler($live, $separats)
    {
        $filecontent = new Content();
        $FRAME = 0.2;
        foreach ($separats as $val) {
            if (!json_decode($val['lvsr_data'], true)['list']) {
                throw new \Exception("have no transfer data");
            }
            foreach (json_decode($val['lvsr_data'], true)['list'] as $sentence) {
                $filecontent->push($sentence['txt'], number_format((explode("-", $sentence['time'])[1] - explode("-", $sentence['time'])[0]) * $FRAME, 2, '.', ''));
            }
        }

        $live->transfer = json_encode(['list' => $filecontent->getArr()], JSON_UNESCAPED_UNICODE);
        $live->save();
    }

    //合并文字 修改
    private function mergeTextEditHandler($live)
    {
        $speech_list = $live->mconvert;
        $filecontent = new Content();
        foreach ($speech_list as $val) {
            $filecontent->push($val['editor'] ? $val['editor'] : $val['transfer'], $val['pcmtime'], $sc = $val['subsection']);
        }
        $live->transfer = json_encode(['list' => $filecontent->getArr()], JSON_UNESCAPED_UNICODE);
        $live->save();
    }

    public function FilePopFromList()
    {
        self::$redis = RedisPackage::getInstance();
        $data = self::$redis->mergeQueuePop();
        return json_decode($data, true);
    }
}
